<template>
  <u-navbar :autoBack="true" title="忘记密码"></u-navbar>
  <view class="wrap">
    <view class="remind-text">忘记密码？</view>
    <view class="tip">请根据手机号修改您的登录密码</view>

    <u-form class="form" :model="model" :rules="rules" ref="uForm" labelPosition="top">
      <!-- 手机号输入 -->
      <u-form-item label="手机号" prop="phone" label-width="150" :borderBottom="true">
        <u-input v-model="model.phone" placeholder="请输入注册手机号" type="number" maxlength="11" border="none">
        </u-input>
      </u-form-item>

      <!-- 图形验证码 -->
      <u-form-item label="图形验证码" prop="imageCaptcha" label-width="150" :borderBottom="true">
        <view class="captcha-row">
          <u-input v-model="model.imageCaptcha" placeholder="请输入图形验证码" maxlength="4" border="none">
          </u-input>
          <image :src="captchaImage" class="captcha-img" @click="refreshCaptcha" mode="aspectFill">
          </image>
        </view>
      </u-form-item>

      <!-- 短信验证码 -->
      <u-form-item label="短信验证码" prop="smsCode" label-width="150" :borderBottom="true">
        <view class="captcha-row">
          <u-input v-model="model.smsCode" placeholder="请输入短信验证码" maxlength="6" border="none">
          </u-input>
          <u-button class="send-btn" :disabled="isCounting" @click="sendSMSCode" size="mini">
            {{ isCounting ? `${countdown}秒后重试` : '获取验证码' }}
          </u-button>
        </view>
      </u-form-item>

      <!-- 新密码 -->
      <u-form-item label="新密码" prop="newPassword" label-width="150" :borderBottom="true">
        <u-input type="password" v-model="model.newPassword" placeholder="请输入新密码" border="none">
          <template #suffix>
            <u-icon :name="showPassword ? 'eye-fill' : 'eye-off'" @click="showPassword = !showPassword" size="22">
            </u-icon>
          </template>
        </u-input>
      </u-form-item>

      <!-- 确认密码 -->
      <u-form-item label="确认密码" prop="confirmPassword" label-width="150" :borderBottom="true">
        <u-input type="password" v-model="model.confirmPassword" placeholder="请确认新密码" border="none">
        </u-input>
      </u-form-item>
    </u-form>

    <view class="info">
      <view class="dot"></view>
      <view>密码需8-16位，包含字母+数字组合（不能是纯数字）</view>
    </view>

    <view class="form-footer">
      <u-button class="btn" type="primary" @click="submit">提交</u-button>
    </view>
  </view>
</template>

<script>
// import { getCaptcha, sendSms, resetPassword } from '@/apis/cloud/forgot.js';
// import CryptoJS from 'crypto-js';
import baseApi from '@/apis/cloud/base.js';
function generateUUID () {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    const r = Math.random() * 16 | 0;
    const v = c === 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}
export default {
  data () {
    // 密码复杂度校验方法
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入密码'));
      }
      if (value.length < 8 || value.length > 16) {
        return callback(new Error('密码长度需8-16位'));
      }
      if (/^\d+$/.test(value)) {
        return callback(new Error('密码不能是纯数字'));
      }
      if (!/[a-zA-Z]/.test(value) || !/\d/.test(value)) {
        return callback(new Error('需包含字母+数字组合'));
      }
      callback();
    };

    // 确认密码校验
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.model.newPassword) {
        return callback(new Error('两次输入的密码不一致'));
      }
      callback();
    };

    return {
      model: {
        phone: '',
        imageCaptcha: '',
        smsCode: '',
        newPassword: '',
        confirmPassword: ''
      },
      rules: {
        phone: [
          {
            required: true,
            message: '请输入手机号',
            trigger: ['blur', 'change']
          },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号格式不正确',
            trigger: ['blur', 'change']
          }
        ],
        imageCaptcha: [
          {
            required: true,
            message: '请输入图形验证码',
            trigger: ['blur', 'change']
          },
          {
            min: 4,
            max: 4,
            message: '验证码为4位字符',
            trigger: ['blur', 'change']
          }
        ],
        smsCode: [
          {
            required: true,
            message: '请输入短信验证码',
            trigger: ['blur', 'change']
          },
          {
            min: 4,
            max: 4,
            message: '验证码为4位数字',
            trigger: ['blur', 'change']
          }
        ],
        newPassword: [
          {
            required: true,
            message: '请输入新密码',
            trigger: ['blur', 'change']
          },
          {
            validator: validatePassword,
            trigger: ['blur', 'change']
          }
        ],
        confirmPassword: [
          {
            required: true,
            message: '请确认新密码',
            trigger: ['blur', 'change']
          },
          {
            validator: validateConfirmPassword,
            trigger: ['blur', 'change']
          }
        ]
      },
      captchaImage: '', // 图形验证码图片
      isCounting: false,    // 倒计时状态
      countdown: 60,        // 短信倒计时
      showPassword: false,  // 密码可见性
      timer: null,           // 倒计时定时器
      captchaKey: '', // 唯一 key
    };
  },
  mounted () {
    this.refreshCaptcha(); // 初始化图形验证码
  },
  methods: {
    // 刷新图形验证码
    async refreshCaptcha () {
      try {
        this.captchaKey = generateUUID();
        this.captchaImage = `https://cloud.mfarmers.com/dist/interface/public/index.php/index/Index/getCaptcha?uuid=${this.captchaKey}&t=${Date.now()}`;
      } catch (error) {
        console.error('获取验证码失败', error);
        uni.$u.toast('获取验证码失败，请重试');
      }
    },

    // 发送短信验证码
    async sendSMSCode () {
      if (!this.model.phone) {
        uni.$u.toast('请输入手机号');
        return;
      }
      if (!this.model.phone.match(/^1[3-9]\d{9}$/)) {
        uni.$u.toast('手机号格式错误');
        return;
      }
      if (!this.model.imageCaptcha) {
        uni.$u.toast('请输入图形验证码');
        return;
      }
      const captchaRes = await baseApi.checkCaptcha({ captcha: this.model.imageCaptcha, uuid: this.captchaKey })
      if (!captchaRes.status) {
        uni.$u.toast(captchaRes.msg);
        this.refreshCaptcha();
        return;
      }
      try {
        const smsRes = await baseApi.sendSms({ send_phone: this.model.phone, worker_phone: this.model.phone, type: 'sms' });
        if (smsRes.status) {
          uni.$u.toast('验证码已发送');
        } else {
          uni.$u.toast('发送验证码失败');
          return;
        }
      } catch (error) {
        console.error('发送短信失败', error);
        uni.$u.toast('发送验证码失败');
        return;
      }

      // 3. 启动倒计时
      this.isCounting = true;
      this.countdown = 60;

      this.timer = setInterval(() => {
        if (this.countdown <= 0) {
          clearInterval(this.timer);
          this.isCounting = false;
          this.countdown = 60;
          return;
        }
        this.countdown--;
      }, 1000);
    },

    // 提交重置请求
    async submit () {
      try {
        // 1. 表单验证
        await this.$refs.uForm.validate();

        // 3. 调用重置接口
        const res = await baseApi.resetPassword({
          account: this.model.phone,
          captcha: this.model.smsCode,
          newPassword: this.model.newPassword
        });

        // 4. 处理结果
        if (res.code === 200) {
          uni.$u.toast('密码修改成功');
          setTimeout(() => uni.navigateBack(), 1500);
        } else {
          uni.$u.toast(res.msg || '修改失败，请重试');
        }
      } catch (error) {
        console.error('表单验证或提交失败', error);
        if (error.error) {
          uni.$u.toast(error.error);
        }
      }
    }
  },
  beforeUnmount () {
    clearInterval(this.timer); // 清理定时器
  }
};
</script>

<style lang="scss">
.wrap {
  height: calc(100vh - 88rpx - var(--status-bar-height));
  padding: 0 30rpx;
  padding-top: calc(88rpx + var(--status-bar-height));
  overflow-y: scroll;
}

.remind-text {
  font-size: 38rpx;
  font-weight: bold;
  margin-top: 60rpx;
  letter-spacing: 2rpx;
}

.tip {
  color: #aaa;
  font-size: 28rpx;
  padding: 20rpx 0;
  letter-spacing: 2rpx;
  margin-bottom: 40rpx;
}

.info {
  display: flex;
  align-items: center;
  color: #aaa;
  padding: 60rpx 0;
  font-size: 24rpx;
}

.dot {
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  background-color: #fa3534;
  margin-right: 20rpx;
  align-self: flex-start;
  margin-top: 12rpx;
}

.form-footer {
  margin-top: 40rpx;
  padding-bottom: 40rpx;

  .btn {
    height: 90rpx;
    border-radius: 45rpx;
    font-size: 32rpx;
  }
}

.captcha-row {
  display: flex;
  align-items: center;
  width: 100%;

  .captcha-img {
    width: 200rpx;
    height: 80rpx;
    margin-left: 20rpx;
    border-radius: 8rpx;
    border: 1rpx solid #e4e7ed;
  }

  .send-btn {
    width: 200rpx;
    margin-left: 20rpx;
    font-size: 24rpx;
    background: #fa3534;
    color: #fff;
    height: 60rpx;
    border-radius: 10rpx;
  }
}
</style>